<template>
  <div class="box">
    <h3>拖动下方滑块完成拼图</h3>
    <div ref="bgImgRef" class="img-box">
      <img class="bg" src="../assets/image/hycdn.jpeg" alt="" />
      <img
        class="hd"
        src="../assets/image/hycdn.png"
        :style="{ left: data.left + 'px', top: data.top + 'px' }"
        alt=""
      />
    </div>
    <div class="btn-box">
      <div
        ref="btnRef"
        class="btn"
        @mousedown="btnMousedown"
        @mouseup="btnMouseup"
        :style="{ left: data.left + 'px' }"
      >
        |||
      </div>
    </div>
  </div>           
</template>

<script lang='ts' setup>
import { reactive, onMounted, toRefs } from "vue";
import { InitImg } from "../pageJs/index";
let $props = defineProps({
  //得到父传子的数据
  top: {
    type: Number,
    default: 45, //默认
  },
});

let $emit = defineEmits(["getPosition"]); //得到父传子的方法

const data = reactive(new InitImg());
const { btnRef, bgImgRef } = toRefs(data); //用ref获取标签
onMounted(() => {
    data.top = $props.top
  data.offsetLeft = data.bgImgRef.offsetLeft;
  document.body.addEventListener("mouseup", btnMouseup);
});
//鼠标按下
var btnMousedown = (e:any) => {
  data.offsetLeft = data.bgImgRef.offsetLeft;
  data.btnleft = e.pageX - data.btnRef.offsetLeft; //鼠标位置 - 按钮距左边的距离（获取鼠标在滑动按钮中左边像素）
  document.body.addEventListener("mousemove", btnMousemove);
};
//滑动的时候只要求鼠标没有松开
var btnMousemove = (e:any) => {
  let x = e.pageX - data.offsetLeft - data.btnleft;
  if (x <= -10) {
    x = -10;
  } else if (x > 285) {
    x = 285;
  } else {
    data.left = x;
  }
};
//松开
var btnMouseup = () => {
  $emit("getPosition", data.left); //给父元素方法getPosition传入data.left
  document.body.removeEventListener("mousemove", btnMousemove);
};
</script>

<style lang="scss" scoped>
html,
body {
  width: 100%;
  height: 100%;
  user-select: none;
}
.box {
  width: 340px;
  height: 265px;
  border: 1px solid #ccc;
  background-color: #ccc;
  margin: 0 auto;
  padding: 6px 10px 10px 10px;
  h3 {
    line-height: 28px;
  }
  .img-box {
    position: relative;
    .bg {
      width: 100%;
    }
    .hd {
      position: absolute;
      height: 68px;
      width: 68px;
      /* top: 45px; */
      left: 26px;
      cursor: pointer;
    }
  }
  .btn-box {
    width: 100%;
    height: 10px;
    border-radius: 5px;
    background: #e4e4e4;
    margin-top: 15px;
    .btn {
      position: relative;
      top: -10px;
      left: 26px;
      width: 55px;
      height: 30px;
      text-align: center;
      letter-spacing: 5px;
      line-height: 30px;
      color: #fff;
      border-radius: 15px;
      background-color: rgb(26, 121, 255);
      box-shadow: rgb(26 121 255 / 52%) 0px 0px 10px 1px;
      cursor: pointer;
    }
  }
}
</style>